package com.ahui.mallchat.common.common.service;

import com.ahui.mallchat.common.common.exception.BusinessException;
import com.ahui.mallchat.common.common.exception.CommonErrorEnum;
import lombok.SneakyThrows;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * Author:ahui
 * Description:
 * Date: 2024/7/23 17:26
 */
@Service
public class LockService {
    @Autowired
    private RedissonClient redissonClient;

    /**
     * 需要等待时间的锁
     * @param key
     * @param waitTime
     * @param timeUnit
     * @param supplier
     * @return
     * @param <T>
     * @throws InterruptedException
     */
    @SneakyThrows
    public <T> T executeWithLock(String key, int waitTime, TimeUnit timeUnit, Supplier<T> supplier) {
        RLock lock = redissonClient.getLock(key);
        boolean success = lock.tryLock(waitTime, timeUnit);
        if (!success){
            throw new BusinessException(CommonErrorEnum.LOCK_LIMIT);
        }
        try {
            return supplier.get();
        }finally {
            lock.unlock();
        }
    }

    /**
     * 不需要等待时间的锁  需要返回值
     * @param key
     * @param supplier
     * @return
     * @param <T>
     * @throws InterruptedException
     */
    public <T> T executeWithLock(String key,Supplier<T> supplier)  {
        return executeWithLock(key,-1,TimeUnit.MILLISECONDS,supplier);
    }

    /**
     * 不需要返回值
     * @param key
     * @param runnable
     * @return
     * @param <T>
     */
    public <T> T executeWithLock(String key,Runnable runnable)  {
        return executeWithLock(key,-1,TimeUnit.MILLISECONDS,()->{
            runnable.run();
            return null;
        });
    }


    /**
     * 会抛异常的 Supplier
     * @param <T>
     */
    @FunctionalInterface
    public interface Supplier<T> {
        T get() throws Throwable;
    }


}
